
<template>
     <el-card class="box-card">
       <template #header>
        <el-button type="primary" :icon="Plus" @click="posttrademark">添加</el-button>
       </template>
       <el-table :data="trademarklist" align="center"  border style="width: 100% ;margin-bottom:20px;">
         <el-table-column label="序号" align="center"  type=index width="80" />
         <el-table-column prop="tmName" align="center"  label="品牌名称" width="180" />
         <el-table-column prop="logoUrl" align="center" label="品牌Logo" >
             <template v-slot = '{row}'>
                <img :src="row.logoUrl" alt="" style="width:100px;height: 100px;">
             </template>
         </el-table-column>
         <el-table-column  label="操作" >
            <template v-slot="{row}">
              <el-button title="修改" :icon="Edit" type="warning" size="small" @click="puttrademark(row)"/>
              <el-button title='删除' :icon="Delete" type="danger" size="small" @click="deltrademark(row)"/>
            </template>
        </el-table-column>
       </el-table>
       <div class="demo-pagination-block">
        <!-- <div class="demonstration">All combined</div> -->
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[3, 5, 8, 10]"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout=" prev, pager, next, jumper,->,sizes,total"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
        <!-- 对话框 -->
        <el-dialog v-model="dialogFormVisible" :title="`${trademarkform.id ? '添加':'修改'}数据`"> {{ trademarkform }}
          <el-form :model="trademarkform" ref="ruleFormRef" :rules="rules">
            <el-form-item label="品牌名称" :label-width="formLabelWidth" prop="tmName">
              <el-input v-model="trademarkform.tmName" autocomplete="off" />
            </el-form-item>
            <el-form-item label="上传图片" :label-width="formLabelWidth" prop="logoUrl">
              <el-upload class="avatar-uploader" :action="`${BASE_URL}/admin/product/upload`"
                :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <img v-if="trademarkform.logoUrl" :src="trademarkform.logoUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
                <template #tip>
                  <div class="el-upload__tip">
                    图片类型 jpg/png/png/webp 最大为 2 MB
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取消</el-button>
              <el-button type="primary" @click="submitForm(ruleFormRef)">
                确定
              </el-button>
            </span>
          </template>
          
        </el-dialog>
     </el-card>
  </template>


<script lang="ts">

    export default {
        name:'trademark'
    }
</script>

<script setup lang="ts">
import { Plus,Edit,Delete } from '@element-plus/icons-vue';
import {onMounted, ref,reactive} from 'vue'
import {reqgetrademarkInfoData,reqpostrademarkInfoData,reqdelrademarkInfoData,reqputrademarkInfoData} from '@/api/Product/Trademark'
import type {trandemarklistmodel ,trandemarkmodel} from '@/api/Product/model/index'
import { ElMessage ,ElMessageBox } from 'element-plus'
import type { UploadProps ,FormInstance, FormRules } from 'element-plus'


const currentPage = ref(1)
const pageSize = ref(3)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const total = ref<number>(0)
//   一页数据发生变化时
const handleSizeChange = (val: number) => {
    pageSize.value = val
    currentPage.value = 1
    gettrademarklistdata()
}
//页码发生变化时
const handleCurrentChange = (val: number) => {
    currentPage.value = val
    gettrademarklistdata()
}
// 列表数据
let trademarklist = ref<trandemarklistmodel>([])
// 请求数据
let gettrademarklistdata = async ()=>{
    let newdata = await reqgetrademarkInfoData(currentPage.value,pageSize.value)
    total.value = newdata.total
    trademarklist.value = newdata.records
    ElMessage.success('数据请求成功')
}

onMounted(()=>{
    gettrademarklistdata()
})

// 对话框
// 对话框显示状态
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
// 初始化表单数据
const inittrademark = () => ({logoUrl:'',tmName:''})
// 表单数据
let trademarkform = reactive<trandemarkmodel>({
  logoUrl:'',
    tmName:''
})
// 点击添加
let posttrademark = ()=>{
  Object.assign(trademarkform,inittrademark())
  delete trademarkform.id
  dialogFormVisible.value = true
  ruleFormRef.value?.clearValidate()
}

// 上传图片

const imageUrl = ref('')

// 上传图片路径
let BASE_URL = import.meta.env.VITE_API_URL
console.log(BASE_URL);

// 上传成功
const handleAvatarSuccess: UploadProps['onSuccess'] = ( response,uploadFile) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  trademarkform.logoUrl = response.data
  ruleFormRef.value?.clearValidate('logoUrl')
}
// 上传图片校验
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  let logoUrltyoelist = ['image/jpeg','image/png','image/png','image/webp']
  if (!logoUrltyoelist.includes(rawFile.type)) {
    ElMessage.error('图片格式为jpg/png/png/webp')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片最大为2MB!')
    return false
  }
  return true
}
// 表单验证
// 表单唯一标识
const ruleFormRef = ref<FormInstance>()

const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: '品牌不能为空', trigger: 'blur' },
    { min: 1, max: 8, message: '字符长度为1-8', trigger: 'blur' },
  ],
  logoUrl: [
    {
      required: true,
      message: '请上传一张图片',
      trigger: 'change',
    },
  ],
})

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      comaddorput()
    } else {
      let errordata = Object.values(fields as object)[0][0].message
      ElMessage.error(errordata)
    }
  })
}

//提交表单成功的回调函数
let comaddorput = async ()=>{
  if(trademarkform.id){
    await reqputrademarkInfoData(trademarkform)
    ElMessage.success('修改数据成功')
  }else{
    await reqpostrademarkInfoData(trademarkform)
    currentPage.value = 1
    ElMessage.success('添加数据成功')
  }
  Object.assign(trademarkform,inittrademark())
  dialogFormVisible.value = false
  gettrademarklistdata()
}

// 修改数据
let puttrademark = (row : trandemarkmodel) =>{
     Object.assign(trademarkform,row)
     dialogFormVisible.value = true
     ruleFormRef.value?.clearValidate()
}

// 删除数据
let deltrademark = (row:trandemarkmodel)=>{
  ElMessageBox.confirm(
    `你确定删除${row.tmName}吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then( async () => {
      await reqdelrademarkInfoData(row.id as number)
      ElMessage({
        type: 'success',
        message: '删除数据成功',
      })
      gettrademarklistdata()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除数据失败',
      })
    })
}





</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
<style scoped>
.el-button--text {
  margin-right: 15px;
}
.el-select {
  width: 300px;
}
.el-input {
  width: 300px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>